<!-- 购物车 -->
<template>
    <view class="page_box" style="background: #f7faff">
        <!-- 顶部 -->
        <view class="head_box back_fff" style="display: flex; top: 0; right: 0; left: 0; padding-top: 42px" v-show="!isEmpty">
            <view style="float: left; margin-top: 16rpx"></view>
            <view style="float: left; margin-top: 25rpx; font-size: 32rpx">购物车</view>
            <view class="tool-box u-flex" style="float: left">
                <!-- <view class="count-box">
					共
					<text class="all-num">{{ cartList.length }}</text>
					件商品
				</view> -->
                <image :src="url + 'icon_xg.png'" class="cart_glicon"></image>
				<button class="u-reset-button set-btn"  v-if="cartList.length>0" @tap="isTool = !isTool">{{ isTool ? '完成' : '管理' }}</button>
                <button class="u-reset-button set-btn"  v-else >{{ isTool ? '完成' : '管理' }}</button>
            </view>
        </view>

        <view class="content_box" style="background: #f7faff">
            <!-- 列表 -->
            <u-checkbox-group placement="column" @change="checkboxGroupChange" activeColor="#3377FF" v-if="!isEmpty">
                <view class="br_24 collect-list mb_24" v-for="(cart, index) in cartList" :key="cart.id">
                    <view class="flex">
                        <!-- <u-checkbox class="u-p-l-10" :name="cart.id" shape="circle" :checked="cart.checked"><view style="height: 160rpx"></view></u-checkbox> -->
                        <image class="img_40 mr_24" style="border-radius: 50%; vertical-align: middle" :src="cart.avatar" mode=" widthFix"></image>
                        <text>{{cart.trade_name}}</text>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                    <view class="u-flex u-row-left u-col-center">
                        <u-checkbox class="u-p-l-10" :name="cart.id" shape="circle" :checked="cart.checked"><view style="height: 160rpx"></view></u-checkbox>
                        <view class="goods-wrap" style="width: 100%">
                            <view class="mb_24 f_28"></view>
                            <shopro-mini-card :image="cart.pic_url" :title="cart.goods_name" @click="product_tz('/pages/index/ProductDetails?id=' + cart.store_goods_id)">
                                <template #describe>
                                    <view class="order-sku u-ellipsis-1">
                                        <text class="order-num">规格：{{ cart.specifications }}</text>
                                    </view>
                                </template>
                                <template #cardBottom>
                                    <view class="order-price-box u-flex u-row-between" @tap.stop style="color: ##ff6401">
                                        <text class="order-price font-OPPOSANS" style="color: ##ff6401">￥{{ cart.price }}</text>
                                        <u-number-box
                                            button-size="24"
                                            :value="cart.number"
                                            :long-press="false"
                                            :min="1"
                                            :step="1"
                                            :index="index"
                                            :max="99"
                                            @minus="changeNum($event, cart)"
                                            @plus="changeNum($event, cart)"
                                            @change="changeNum($event, cart)"
                                        ></u-number-box>
                                    </view>
                                </template>
                            </shopro-mini-card>
                        </view>
                    </view>
                </view>
            </u-checkbox-group>
            <!-- 数据为空 -->
            <shopro-empty v-if="isEmpty" :image="url + 'empty_cart.png'" tipText="购物车空空如也,快去逛逛吧~"></shopro-empty>
        </view>

        <!-- 底部按钮 -->
        <view class="foot_box" v-show="!isEmpty">
            <view class="tools-box u-flex u-row-between">
                <u-checkbox-group @change="onAllSel" activeColor="#ff6400">
                    <u-checkbox activeColor="#3377FF" shape="circle" :label="'全选'" :checked="allSelected"></u-checkbox>
                </u-checkbox-group>
                <view class="u-flex">
                    <view style="font-size: 24rpx" v-show="!isTool">合计：</view>
                    <view style="color: #ff6400; font-size: 24rpx" v-show="!isTool">￥</view>
                    <view class="price font-OPPOSANS" v-show="!isTool">{{ totalCount.totalPrice.toFixed(2) }}</view>
                    <button class="u-reset-button pay-btn" :disabled="!isSel" v-show="!isTool" @tap="onPay">结算({{ totalCount.totalNum }})</button>
                    <button class="u-reset-button del-btn" v-show="isTool" @tap="goodsDelete">删除</button>
                </view>
            </view>
        </view>
        <!-- <shopro-tabbar></shopro-tabbar> -->
    </view>
</template>

<script>
import { mallApi } from '@/common/serve.js';
import shoproEmpty from '@/components/shopro-empty/shopro-empty';
import shoproMiniCard from '@/components/shopro-mini-card/shopro-mini-card';
import { goodsCartList, goodsCartUp, goodsCartDel } from '@/api';
let timer = null;

export default {
    components: {
        shoproEmpty,
        shoproMiniCard
    },
    data() {
        return {
            cartList: [],
            allSelected: false,
            maxStep: 999,
            authType: false,
            isTool: false,
            isLogin: true,
            url: '',
			lat:'',
			lng:'',
        };
    },
    computed: {
        isEmpty() {
            return !this.cartList.length;
        },
        // 购物车数量和总价


        // 是否选择了商品
        isSel() {
            let isSel = false;
            this.cartList.map((item) => {
                if (item.checked) {
                    isSel = true;
                }
            });
            return isSel;
        },
		totalCount() {
		    let totalNum = 0;
		    let totalPrice = 0;
		    this.cartList.filter((item) => {
		        if (item.checked) {
		            totalNum += 1;
		            totalPrice += parseInt(item.number) * (item.price);
		        }
		    });
		    return {
		        totalNum,
		        totalPrice
		    };
		},

        // 活动商品唯一选中可以结算
        isActivityPay() {
            let num = 0;
            let activityNum = 0;
            this.cartList.map((item) => {
                if (item.checked) {
                    num += 1;
                    if (item.cart_type === 'activity') {
                        activityNum += 1;
                    }
                }
            });
            if ((num === 1 && activityNum === 1) || activityNum === 0) {
                return true;
            }
            return false;
        }
    },
    onShow() {
		// var that= this
		// uni.getLocation({
		// 	type: 'wgs84',
		// 	// altitude:true,
		// 	success: function (res) {
		// 		that.lat=res.latitude;
		// 		that.lng=res.longitude;
		// 		console.log('当前位置的经度：' + res.longitude);
		// 		console.log('当前位置的纬度：' + res.latitude);
		// 	}
		// });
        // this.cartList = [
        //   {
        //     goods_num: 5,
        //   },
        // ];
        // this.isLogin && this.getCartList();
        this.getGoodsCartList();
		this.url = this.$.ajax_url2+'imgs/';
        // this.url = this.baseUrl + this.imgPath;
		// this.totalCount()
    },
    onHide() {
        this.isTool = false;
    },
    methods: {
        product_tz(url){
			console.log(url)
			 uni.navigateTo({
			 	url:url
			 })
		},
        getGoodsCartList() {
            // goodsCartList().then(({ data }) => {
            //     this.cartList = data;
            // });
			this.$.ajax(1,"POST","index/shopping_cart_list",{},(res)=>{
			  if(res.code==200){
				 this.cartList = res.data
				 
			  }else{
			     this.$.ti_shi(res.msg);
			  }
			})
        },
        // 更改商品数
        changeNum(e, cart) {
            console.log(e);
            if (!e) {
                return;
            }
            let value = e.value;
            const { id, meta } = cart;
            if (!value) {
                return;
            }
            meta.sku.sum = value;
            console.log(value, id, meta);
            goodsCartUp(id, meta).then((res) => {
                console.log(res);
                this.getGoodsCartList();
            });
        },
        goBack() {
            this.$api.authBack();
        },
        getCartList() {
            mallApi.cartList().then((res) => {
                this.cartList = res;
            });
        },
        changeCartList(params) {
            mallApi.cartEdit(params).then((res) => {});
        },
        // 到达最小值
        onMin(g) {
            uni.showModal({
                title: '删除提示',
                confirmColor: '#f0c785',
                content: `是否确认从购物车中删除此商品?`,
                success: (res) => {
                    res.confirm && this.changeCartList({ cart_list: [g.id], act: 'delete' });
                }
            });
        },

        // 单选
        // checkboxGroupChange(ids) {
        //     this.cartList = this.cartList.map((v) => {
        //         v.checked = false;
        //         if (ids.indexOf(v.id) > -1) {
        //             v.checked = true;
        //         }
        //         return v;
        //     });

        //     this.checkCartList();
        // },
        // 店铺勾选id集合
        checkboxGroupChange(ids) {
            // 全选
            if (ids.length >= this.cartList.length) {
                this.allSelected = true;
            } else {
                this.allSelected = false;
            }
            this.cartList = this.cartList.map((v) => {
                if (ids.indexOf(v.id) > -1) {
                    v.checked = true;
                } else {
                    v.checked = false;
                }
                return v;
            });
        },
        // 全选
        onAllSel() {
            let that = this;
            this.changeAllSellect();
            this.getAllSellectCartList(that.allSelected);
        },

        // 结算
        onPay() {
			let that = this;
			let cartList = this.cartList;
			let selectedIdsArray = [];
			for (let i = 0; i < this.cartList.length; i++) {
			   
			        if (this.cartList[i].checked) {
			            selectedIdsArray.push(this.cartList[i].id);
			        }
			}
			this.$.ajax(1,"POST","index/add_order",{
				ids:selectedIdsArray.join(','),
				is_shoppingcart:1,
				lat:this.lat,
				lng:this.lng,
				// money:this.infos.goods_image
			},(res)=>{
			  if(res.code==200){
				    console.log(res)
					uni.navigateTo({
						url:'/pages/index/PaymentOrder?order_id='+res.order_id+'&product_type=1'
					})
				 	// this.infos = res.data;
					 // console.log(this.infos)
			  }else{
			     this.$.ti_shi(res.msg);
			  }
			})
        },
        // 删除
        goodsDelete() {
            let that = this;
            let cartList = this.cartList;
            let selectedIdsArray = [];
            for (let i = 0; i < this.cartList.length; i++) {
               
                    if (this.cartList[i].checked) {
                        selectedIdsArray.push(this.cartList[i].id);
                    }
               
            }
			console.log(selectedIdsArray)
            this.$.ajax(1,"POST","index/shopping_cart_del",{
				ids:selectedIdsArray.join(',')
			},(res)=>{
              if(res.code==200){
				   this.$.ti_shi(res.msg)
				  setTimeout(() => {
				  	 this.getGoodsCartList();
					 this.isTool=false
				  }, 1000);
              }else{
                 this.$.ti_shi(res.msg);
              }
            })
           
        },
        // 切换全选。
        changeAllSellect() {
            this.allSelected = !this.allSelected;
            // 店铺勾选
            if (this.allSelected) {
                this.cartList.forEach((i) => {
                    i.checked = true;
                    // 勾选店铺下 的商品
                    // i.children.forEach((j) => {
                    //     j.checked = true;
                    // });
                });
            } else {
                // 取消店铺勾选
                this.cartList.forEach((i) => {
                    i.checked = false;
                    // 取消勾选店铺下 的商品
                    // i.children.forEach((j) => {
                    //     j.checked = false;
                    // });
                });
            }
        },
        // 全选设置
        getAllSellectCartList(flag) {
            this.cartList = this.cartList.map((item) => {
                item.checked = flag;
                return item;
            });
        },
        // 全选检测
        checkCartList() {
            let all = true;
            this.cartList.map((item) => {
                if (!item.checked) {
                    all = false;
                }
            });
            this.allSelected = all;
        },
        // 是否购物车数据检测
        getCheckCart() {
            let obj = {};
            this.cartList.map((item) => {
                obj[item.goods_id] = {
                    num: item.goods_num,
                    cartOrderId: item.id
                };
            });
            this.checkCart = obj;
        },
        // 勾选单个
        childCheckDone(obj, ev) {
            for (let i = 0; i < this.cartList.length; i++) {
                // for (let j = 0; j < this.cartList[i].children.length; j++) {
                // 	if (obj.id == this.cartList[i].children[j].id) {
                // 		this.cartList[i].children[j].checked = ev;
                // 	}
                // }
            }

            this.isAll();
        },
        // 判断是否是全选
        isAll() {
            this.$nextTick(() => {
                let stu = true;
                for (let i = 0; i < this.cartList.length; i++) {
                    if (this.cartList[i].checked === false) {
                        stu = false;
                        break;
                    }
                }
                this.allSelected = stu;
                stu = true;
            });
        },

        childrenChange(obj, ids) {
            for (let i = 0; i < this.cartList.length; i++) {
                for (let j = 0; j < this.cartList[i].children; j++) {
                    for (let k = 0; k < ids.length; k++) {
                        if (ids[k] == this.cartList[i].children[j].id) {
                            this.cartList[i].children[j].checked = true;
                        }
                    }
                }
            }
            if (ids.length == obj.children.length) {
                for (let i = 0; i < this.cartList.length; i++) {
                    if (obj.id == this.cartList[i].id) {
                        this.cartList[i].checked = true;
                    }
                }
            } else {
                for (let i = 0; i < this.cartList.length; i++) {
                    if (obj.id == this.cartList[i].id) {
                        this.cartList[i].checked = false;
                    }
                }
            }
        }
    }
};
</script>

<style lang="scss">
@import '@/uni_modules/uview-ui/common.scss';
// 总计商品
.icon_check {
    width: 36rpx;
    height: 36rpx;
    border: 2px solid #ddd;
    border-radius: 50%;
}
.icon_check.active {
    background: blue;
    border: 2px solid blue;
}
.head_box {
    padding: 20rpx 15rpx;
    .tool-box {
        height: 90rpx;
        padding: 0 30rpx;

        .count-box {
            font-size: 26rpx;
            color: #999;

            .all-num {
                color: #a8700d;
            }
        }

        .set-btn {
            background: none;
            font-size: 26rpx;
            color: #999;
        }
        .cart_glicon {
            width: 30rpx;
            height: 30rpx;
            margin-right: 10rpx;
        }
    }
}

// 空白页
.empty-box {
    flex: 1;
    width: 100%;
    height: 100%;
}

// 购物车项
.collect-list {
    background: #fff;
    // width: 750rpx;
    margin: 12px 16px 0;
    padding: 20rpx;

    // 商品卡片包裹
    .goods-wrap {
        position: relative;

        .order-sku {
            font-size: 24rpx;
            font-weight: 400;
            color: rgba(153, 153, 153, 1);
            margin-bottom: 20rpx;

            .order-num {
                width: 150px;
                display: inline-block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        .order-price-box {
            .status-btn {
                height: 32rpx;
                border-radius: 15rpx;
                font-size: 20rpx;
                font-weight: 400;
                padding: 0 10rpx;
                margin-left: 20rpx;
                background: rgba(233, 183, 102, 0.16);
            }

            .order-price {
                font-size: 28rpx;
                color: #ff6400;
            }
        }

        .lose-box {
            position: absolute;
            z-index: 10;
            width: 100%;
            height: 100%;
            background-color: rgba(#fff, 0.8);

            .icon-yishixiao {
                position: absolute;
                bottom: 0rpx;
                right: 80rpx;
                font-size: 140rpx;
                line-height: 140rpx;
                color: #dbdbdb;
                transform: rotate(-30deg);
            }

            .invalid-tips {
                position: absolute;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                margin: auto;
                width: 400rpx;
                height: 60rpx;
                border-radius: 30rpx;
                color: #fff;
                background-color: rgba(#000, 0.35);
            }
        }
    }

    .tag-box {
        .tag1 {
            line-height: 36rpx;
            padding: 0 8rpx;
            font-size: 18rpx;
            color: rgba(#fff, 0.9);
            display: inline-block;
            box-sizing: border-box;
        }

        .tag2 {
            line-height: 34rpx;
            padding: 0 8rpx;
            font-size: 18rpx;
            background: #fff;
            display: inline-block;
            box-sizing: border-box;
        }
    }

    .price-box {
        width: 420rpx;

        .price {
            color: #e1212b;
        }
    }
}

.tools-box {
    height: 100rpx;
    width: 750rpx;
    padding: 0 30rpx;
    background: #fff;

    .check-all {
        font-size: 26rpx;

        .check-all-radio {
            transform: scale(0.7);
            color: #e9b564;
        }
    }

    .price {
        color: #ff6400;
        font-size: 36rpx;
        margin-right: 30rpx;
    }

    .pay-btn {
        line-height: 70rpx;
        background: #ff6400 !important;
        border-radius: 10rpx;
        padding: 0 20rpx;
        color: white !important;
    }

    .del-btn {
        width: 150rpx;
        line-height: 70rpx;
        background: #ff6400 !important;
        border-radius: 10rpx;
        color: white !important;
    }
}
.u-number-box {
    border-radius: 0 !important;
}
.u-number-box view {
    background: #f7faff !important;
}
.u-number-box input {
    background: #f7faff !important;
}
.u-number-box text {
    font-size: 24rpx !important;
}
</style>
